<template>
  <main>
    <div class="m1">
      <div class="history">
        <div :class="'content ' + (i.ai ? '' : 'me')" v-for="(i, j) in chats" :key="j">
          <img class="head" :src="i.ai ? '/assets/千与.png' : '/assets/千寻.png'" />
          <div class="texts">
            <div class="time">{{ new Date(i.created * 1000).toLocaleString() }}</div>
            <div class="text">{{ i.text }}</div>
          </div>
        </div>
      </div>
      <!-- <div class="chat" @keydown="keydown">
      <textarea v-model="chat" auto-height placeholder=""></textarea>
      <button v-if="!waiting" class="send" @click="send()">发送</button>
      <button v-else class="send" @click="stop()">停止</button>
    </div> -->
      <view class="bottom">
        <view class="input">
          <textarea id="textareaMsg" class="inputs" v-autoheight placeholder="" v-model="chat" maxlength="2048"></textarea>
          <img class="sendimg " @click="send()" src="../public/assets/发送.png">
        </view>
      </view>
    </div>
  </main>
</template>

<script>
function send(text) {
  let data = {
    prompt: text,
    model: "text-davinci-003",
    max_tokens: 2048,
  }
  var promise = new Promise((resolve, reject) => {
    var req = new XMLHttpRequest();
    req.onreadystatechange = async () => {
      if (req.readyState == 4) {
        if (req.status == 200) {
          resolve(JSON.parse(req.responseText));
        } else {
          const error = { code: req.status, msg: req.statusText };
          reject(error);
        }
      }
    }
    req.open("POST", "https://api.openai.com/v1/completions", true);
    req.setRequestHeader("Content-Type", "application/json");
    req.setRequestHeader("Authorization", `Bearer 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`);
    req.send(JSON.stringify(data));
  });
  return promise;
}

export default {
  name: 'App',
  data() {
    return {
      chat: undefined,
      waiting: false,
      last: {},
      chats: [],
    }
  },
  directives: {
    //用于自适应文本框的高度
    autoheight: {
      updated: function (el) {
        var Msg = el.value;
        if (Msg == "") {
          el.style.height = "43px"
        } else {
          el.style.height = 'auto'
          el.style.height = el.scrollHeight + 'px'
        }
      }
    }
  },
  computed: {
    chatlist() {
      if (this.last)
        return [...this.chats, this.last];
      else
        return this.chats;
    },
  },
  methods: {
    async send() {
      const content = this.chat;
      if (!content)
        return;

      this.chats.unshift({
        created: (Date.now() / 1000) | 0,
        text: content,
      });

      this.chat = undefined;
      this.waiting = true;
      const parent = this.chats.length ? this.chats[this.chats.length - 1] : {};

      const last = await send(content, {
        conversationId: parent.conversationId,
        parentMessageId: parent.id,
        onProgress: this.waitResponse,
      })

      this.waiting = false;
      this.last = null;
      if (last) {
        this.chats.unshift({ created: last.created, text: last.choices[0].text.trimStart(), ai: true });
        if (this.chats.length > 100)
          this.chats.pop();
        localStorage.setItem("chats", JSON.stringify(this.chats));
      }
    },
    waitResponse(partialResponse) {
      if (!this.waiting)
        return;
      this.last = partialResponse;
    },
    stop() {
      this.waiting = false;
    },
    keydown(e) {
      if (e.keyCode == 13) {
        this.send();
        setTimeout(() => {
          this.chat = undefined;
        }, 100)
      }
    },
  },
  mounted() {
    const chats = localStorage.getItem("chats");
    if (chats)
      this.chats = JSON.parse(chats);
  }
}
</script>

<style lang="scss" scoped>
main {
  display: flex;
  flex-direction: column-reverse;
  // height: 98vh;

  .history {
    flex: 1;
    padding-bottom: 10px;

    .content {
      display: flex;

      align-items: flex-start;
      margin: 10px;
      // border: 1px solid #090000;
      //边框调试样式时使用

      .texts {
        margin: 0 10px;
        min-height: 70px;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        white-space: normal;
        // border: 1px solid #090000;

        .time {
          color: rgba(255, 255, 255, 0.347);
          margin-bottom: 5px;
        }

        .text {
          background-color: #3f4555;
          color: #a8babc;
          border-radius: 8px;
          padding: 8px 8px;
          // flex: auto;

        }
      }

      .head {
        width: 50px;
        height: auto;
        object-fit: contain;
        border-radius: 50%;
      }
    }

    .me {
      flex-direction: row-reverse;
      text-align: right;

      .texts {
        margin: 0 10px;
        min-height: 70px;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        white-space: normal;
        // border: 1px solid #090000;
      }
    }
  }

  .bottom {
    background: #0b101d;
    position: fixed;
    bottom: 0px;
    padding-top: 0px;
    padding-bottom: 10px;
    width: 100%;
  }

  .input {
    display: flex;
    /* background: bisque; */
    width: 100%;
    align-items: flex-end;
    box-sizing: border-box;

  }

  .inputs {
    margin: 10px 10px 0 15px;
    padding: 5px 5px 5px 5px;
    min-height: 43px;
    max-height: 150px;
    background: #3f4555;
    flex: auto;
    border-radius: 5px;
    font-size: 15px;
    resize: none;
    color: white;
  }
.inputs::-webkit-scrollbar {
  width: 0;
}
  .sendimg {
margin-bottom: 2.5px;
margin-right: 11px;
    height: 37px;
    width: 37px;
    flex: none;
  }
}

@media screen and (min-width:660px) {
  main {
    display: flex;
    flex-direction: row;
    justify-content: center;

    .bottom {
      width: 40rem;
    }
  }

  .m1 {
    width: 40rem;
    display: flex;
    flex-direction: row;
    justify-content: center;
  }
}

</style>
